package com.games.portal.service;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;

/**
 * Starts the intent service and pass the callback response back to the activity 
 * @author hirsche
 *
 */
public class Html5ServiceHelper {

	public static String ACTION_REQUEST_RESULT = "REQUEST_RESULT";
	public static String EXTRA_REQUEST_ID = "EXTRA_REQUEST_ID";
	public static String EXTRA_RESULT_CODE = "EXTRA_RESULT_CODE";
	private static final String REQUEST_ID = "REQUEST_ID";

	private Context context ;
	private static Html5ServiceHelper helper  = new Html5ServiceHelper();
	
	private Html5ServiceHelper() {
	}
	
	public static Html5ServiceHelper getInstance(Context context) {
		helper.setContext(context);
		return helper;
	}

	public void setContext(Context context) {
		this.context = context;
	}
	
	/**
	 * Start the intent service
	 */
	public void getGamesList() {
		ResultReceiver serviceCallback = new ResultReceiver(null){

			@Override
			protected void onReceiveResult(int resultCode, Bundle resultData) {
				handleGetGameListResponse(resultCode, resultData);
			}

		};
		
		Intent intent = new Intent(this.context, Html5Service.class);
		intent.putExtra(Html5Service.METHOD_EXTRA, Html5Service.METHOD_GET);
		intent.putExtra(Html5Service.RESOURCE_TYPE_EXTRA, Html5Service.RESOURCE_TYPE_GAMES);
		intent.putExtra(Html5Service.SERVICE_CALLBACK, serviceCallback);

		this.context.startService(intent);


	}
	
	/**
	 * Send the response back to the activity
	 * @param resultCode
	 * @param resultData
	 */
	private void handleGetGameListResponse(int resultCode, Bundle resultData){


		Intent origIntent = (Intent)resultData.getParcelable(Html5Service.ORIGINAL_INTENT_EXTRA);

		if(origIntent != null){
			long requestId = origIntent.getLongExtra(REQUEST_ID, 0);


			Intent resultBroadcast = new Intent(ACTION_REQUEST_RESULT);
			resultBroadcast.putExtra(EXTRA_REQUEST_ID, requestId);
			resultBroadcast.putExtra(EXTRA_RESULT_CODE, resultCode);

			this.context.sendBroadcast(resultBroadcast);

		}
	}
}


